<template>
  <div class="w1 h1" ref="chart-dom"></div>
</template>
<script>
import { getIndexElectricity } from '@/api'
let resize = null
const barOption = {
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['本月累计用电量', '上月累计用电量'],
    right: 5,
    top: 3,
    textStyle: {
      color: '#fff'
    }
  },
  grid: {
    bottom: '15%',
    left: '16%',
    right: '10%',
    top: '20%'
  },
  xAxis: {
    type: 'category',
    data: [...Array(31)].map((t, i) => ++i + '日'),
    axisLabel: {
      show: true,
      textStyle: {
        color: '#fff'
      }
    },
    //  隐藏坐标轴
    axisLine: {
      show: false
    },
    // 去除坐标轴上的刻度线
    axisTick: {
      show: false
    },
    // 网格是否显示
    splitLine: {
      show: false
    }
  },
  yAxis: [
    {
      name: 'kWh',
      nameTextStyle: {
        color: '#fff',
        padding: [0, 20, 0, 0]
      },
      type: 'value',
      axisLabel: {
        show: true,
        textStyle: {
          color: '#fff'
        }
      },
      //  隐藏坐标轴
      axisLine: {
        show: false
      },
      // 去除坐标轴上的刻度线
      axisTick: {
        show: false
      },
      // 网格是否显示
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '本月累计用电量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#08ED74'
      }
    },
    {
      name: '上月累计用电量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#53FDFC'
      }
    }
  ]
}

export default {
  props: {
    companyId: {
      type: String,
      default: ''
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    companyId() {
      this.init()
    }
  },
  beforeDestroy() {
    if (resize) {
      window.removeEventListener('resize', resize)
    }
  },
  methods: {
    async init() {
      const vm = this
      const companyId = vm.companyId
      if (!companyId) {
        return
      }
      const params = { companyId }
      const { code, data } = await getIndexElectricity(params)
      if (code !== 200) {
        return
      }
      vm.$nextTick(() => {
        const dom = vm.$refs['chart-dom']
        const echartInstance = vm.echarts.init(dom)
        const { cMonthUseList, lMonthUseList } = data
        const option = { ...barOption }
        option.series[0].data = cMonthUseList
        option.series[1].data = lMonthUseList
        echartInstance.setOption(option)
        resize = () => echartInstance.resize()
        window.addEventListener('resize', resize)
      })
    }
  }
}
</script>
